package manager;

import java.io.IOException;
import java.util.ArrayList;

import manager.interfaces.ICustomerManager;
import util.CustomerIO;
import util.FileIOHelper;
import vo.Customer;
import exception.NotFoundException;

public class CustomerManager implements ICustomerManager{

	private static CustomerManager customerManager = new CustomerManager();
	ArrayList<Customer> customerList;

	private CustomerManager() {
		customerList = new ArrayList<Customer>();		
	}

	public static CustomerManager getInstance() {
		if(null == customerManager) {
			return new CustomerManager();
		} else {
			return customerManager;
		}		
	}



	@Override
	public Customer findCustomer(int customId) throws NotFoundException  {

		Customer seekedCustomer = null;

		for(int i = 0; i < customerList.size(); ++i) {

			Customer customer = customerList.get(i);

			// 사용자로부터 입력받은 고객번호를 기반으로 검색
			if(customId == customer.getId()){
				seekedCustomer = customer;
			}
		}

		// 없는 경우 익셉션 처리
		if(null == seekedCustomer) {
			throw new NotFoundException();
		}
		

		return seekedCustomer;
	}

	@Override
	public void unregistCustomer(int customerId) throws NotFoundException {

		boolean isValidValue = false;
		
		for(int i = 0; i < customerList.size(); ++i){
			
			Customer customer = customerList.get(i);
			// 고객 번호로 검색하여 제거
			if(customer.getId() == customerId) {
				isValidValue = true;
				customerList.remove(i);
			}				
		}
		// 검색이 안된 경우 익셉션 처리
		if(!isValidValue)
			throw new NotFoundException();
	}

	@Override
	public boolean registCustomer(Customer customer) {
		
		try{
			// 고객 리스트에 추가
			customerList.add(customer);
			// 파일에 쓰기
			saveCustomerList();
		} catch(Exception e) {
			e.printStackTrace();
			return false;
		}
		
		return true;
	}

	@Override
	public void saveCustomerList() throws IOException {
		
		FileIOHelper IOHelper = new FileIOHelper();
		final String tab = "    ";
		StringBuilder sb = new StringBuilder();

		for(int i = 0; i < customerList.size(); ++i)
		{
			Customer customer = customerList.get(i);
			// 형식에 맞추어 스트링 생성
			
			sb.append("고객 번호 : " + customer.getId() + tab
					+ "고객명 : " + customer.getName() + tab
					+ "전화번호 :" + customer.getTelPhone() + tab
					+ "생일 : " + customer.getBirthDate() + "\n");
		}
		// 파일 쓰기
		IOHelper.writeFile("custom.txt", sb.toString());

	}

}
